package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import model.GameClient;

public class CreateGameListener implements ActionListener
{
	private GameClient gameClient;

	public CreateGameListener(GameClient gameClient)
	{
		super();
		this.gameClient = gameClient;
	}

	public void actionPerformed(ActionEvent e)
	{
		if (gameClient.checkConnected() == true)
		{
			createGame();
		}
		else
		{
			JOptionPane.showMessageDialog(gameClient.getContentPane(),
					"Please connect to the server\n"
							+ "before creating a new game.", "Not Connected",
					JOptionPane.ERROR_MESSAGE);
		}
	}

	public synchronized void createGame()
	{
		try
		{
			// Scenario 1
			// Send string 5 to the server to let it know that we wish to create
			// a gameState

			gameClient.getOutputToServer().write(5);
			gameClient.getOutputToServer().flush();

			// Scenario 2
			// Get input from the Server side, reads the boolean that is
			// returned
			// boolean create = gameClient.getInputFromServer().readBoolean();

			System.out.println("Before create " + 1);
			int create = gameClient.getInputFromServer().read();
			System.out.println("After create " + 2);

			// Scenario 3
			// 1 from the server means SUCCESS! Proceed to create new game.
			// Otherwise means fail and inform Game Creator Client of error
			if (create == 1)
			{
				// SERVER WILL PUT US IN A GAME NOW
				// here is where we wait start a new game
				// notifyAll();
				// by choosing a side

				gameClient.chooseSide();

				// Server will create a monster once all clients have chosen a
				// side
				// After a monster has been created, wait a few seconds then
				// start game

				// if (server responds with a number){
				// gameClient.startGame();
				// }
			}
			else
			{
				JOptionPane
						.showMessageDialog(
								gameClient.getContentPane(),
								"Insufficient clients.\nPlease "
										+ "try again later when more people are connected",
								"Not Enough Clients", JOptionPane.ERROR_MESSAGE);
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}
}
